﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace Platform.Storage.Entity
{
	/// <summary>
	/// Modelo do banco de dados
	/// </summary>
	internal sealed class DbContextModelBuilder : DbModelBuilder
	{
		private const int ReversedTokenIdSize = 64;


		/// <summary>
		/// 
		/// </summary>
		public DbContextModelBuilder()
		{
			this.MapFieldValueEntity();
			this.MapDataObjectRelationshipEntity();
		}

		/// <summary>
		/// Mapeamento da entidade campo e valor
		/// </summary>
		private void MapFieldValueEntity()
		{
			var entity = this.Entity<FieldValue>();

			entity.ToTable( "fieldValues", "platform" );
			entity.HasKey(
				f => new
				{
					f.LoweredFieldName,
					f.ReversedTokenId
				} );

			entity.Property( f => f.LoweredFieldName ).HasMaxLength( 256 );
			entity.Property( f => f.ReversedTokenId ).HasMaxLength( ReversedTokenIdSize );
			entity.Property( f => f.FieldName ).HasMaxLength( 256 ).HasColumnName( "OriginalFieldName" );
			entity.Property( f => f.TextValue )
				.HasColumnName( "TextValue" )
				.IsOptional()
				.IsUnicode()
				.HasMaxLength( 4000 );
			entity.Property( f => f.BinValue )
				.HasColumnName( "Value" )
				.HasMaxLength( 512 );
			entity.Property( f => f.CreatedOn );
			entity.Property( f => f.UpdatedOn );
		}

		/// <summary>
		/// Mapeamento entre o relacionamento entre os documentos
		/// </summary>
		private void MapDataObjectRelationshipEntity()
		{
			var entity = this.Entity<DataObjectRelationship>();

			entity.ToTable( "dataObjectRelationships", "platform" );
			entity.HasKey(
				f => new
				{
					f.ParentLoweredFieldName,
					f.ParentReversedTokenId,
					f.Order
				} );

			entity.Property( f => f.ParentLoweredFieldName ).HasMaxLength( 256 );
			entity.Property( f => f.ParentOriginalFieldName ).HasMaxLength( 256 );
			entity.Property( f => f.ParentReversedTokenId ).HasMaxLength( ReversedTokenIdSize );
			entity.Property( f => f.Order ).HasColumnName( "Order" );

			entity.Property( f => f.ChildLoweredName ).HasMaxLength( 256 );
			entity.Property( f => f.ChildReversedTokenId ).HasMaxLength( ReversedTokenIdSize );

			entity.Property( f => f.CreatedOn );
			entity.Property( f => f.UpdatedOn );
		}
	}

}
